from fastapi import APIRouter, Depends, Form, Request, Query, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel
from ..models import get_db, Title, User, WebsiteConfig
from ..auth import get_current_user
from ..utils import paginate_query
import os
from fastapi.templating import Jinja2Templates

# 状态切换请求模型
class ToggleStatusRequest(BaseModel):
    new_status: bool

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 标题列表页面
@router.get("/titles", response_class=HTMLResponse)
async def admin_titles(
    request: Request, 
    page: int = Query(1, ge=1), 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    query = db.query(Title).order_by(Title.id)
    pagination = paginate_query(query, page, 20)
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="gradient")
    
    return templates.TemplateResponse("admin/titles.html", {
        "request": request, 
        "titles": pagination["items"],
        "current_page": pagination["current_page"],
        "total_pages": pagination["total_pages"],
        "total_items": pagination["total_items"],
        "page_size": pagination["page_size"],
        "current_user": current_user,
        "config": config
    })

# 添加标题页面
@router.get("/titles/add", response_class=HTMLResponse)
async def admin_add_title(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/title-form.html", 
        {"request": request, "action": "add", "current_user": current_user, "config": config}
    )

# 编辑标题页面
@router.get("/titles/edit/{title_id}", response_class=HTMLResponse)
async def admin_edit_title(
    request: Request, 
    title_id: int, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    title = db.query(Title).filter(Title.id == title_id).first()
    if not title:
        raise HTTPException(status_code=404, detail="标题不存在")
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/title-form.html", 
        {"request": request, "title": title, "action": "edit", "current_user": current_user, "config": config}
    )

# 保存标题
@router.post("/titles/save")
async def save_title(
    id: Optional[int] = Form(None),
    content: str = Form(...),
    is_active: bool = Form(False),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    if id:
        title_obj = db.query(Title).filter(Title.id == id).first()
        if not title_obj:
            raise HTTPException(status_code=404, detail="标题不存在")
        title_obj.content = content
        title_obj.status = is_active
    else:
        title_obj = Title(
            content=content,
            status=is_active
        )
        db.add(title_obj)
    db.commit()
    return RedirectResponse(url="/admin/titles", status_code=302)

# 删除标题
@router.post("/titles/delete/{title_id}")
async def delete_title(
    title_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    title = db.query(Title).filter(Title.id == title_id).first()
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not title:
        if is_ajax:
            return {"success": False, "message": "标题不存在"}
        else:
            raise HTTPException(status_code=404, detail="标题不存在")
    
    db.delete(title)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "删除成功"}
    else:
        return RedirectResponse(url="/admin/titles?message=删除成功", status_code=302)

# 批量删除标题
@router.post("/titles/batch-delete")
async def batch_delete_titles(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    form_data = await request.form()
    title_ids = form_data.getlist("title_ids")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not title_ids:
        if is_ajax:
            return {"success": False, "message": "请选择要删除的标题"}
        else:
            return RedirectResponse(url="/admin/titles?message=请选择要删除的标题", status_code=302)
    
    # 将字符串ID列表转换为整数列表
    title_ids = [int(id) for id in title_ids]
    # 批量删除选中的标题
    db.query(Title).filter(Title.id.in_(title_ids)).delete(synchronize_session=False)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "批量删除成功"}
    else:
        return RedirectResponse(url="/admin/titles?message=批量删除成功", status_code=302)

# 切换标题状态
@router.post("/titles/toggle-status/{title_id}")
async def toggle_title_status(
    title_id: int,
    request_data: ToggleStatusRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找标题
        title = db.query(Title).filter(Title.id == title_id).first()
        
        if not title:
            return JSONResponse(
                content={"success": False, "message": "标题不存在"},
                status_code=404
            )
        
        # 更新状态（这里应该是取反当前状态，而不是直接使用new_status）
        title.status = not title.status
        db.commit()
        
        status_text = "启用" if title.status else "禁用"
        return JSONResponse(
            content={"success": True, "message": f"标题{status_text}成功", "new_status": title.status}
        )
    except Exception as e:
        db.rollback()
        return JSONResponse(
            content={"success": False, "message": f"状态切换失败: {str(e)}"},
            status_code=500
        )